package org.dragonnova.meetingclient.core.net.socket;

import org.dragonnova.meetingclient.core.message.Message;

import java.net.DatagramPacket;
import java.net.SocketAddress;

/**
 * * 指令格式：
 * ****************************** *
 * **   HEADER 2 bytes         ** *
 * **   TYPE  1 bytes          ** *
 * **   LENGTH 4 bytes         ** *
 * **   DATA   ? bytes         ** *
 * **   CS     1 bytes         ** *
 * **   END    2 bytes         ** *
 * ****************************** *
 */

/**
 * Created by hucn on 2016/06/02 16:08.
 * Author: hucn
 * Email: thinkdata@163.com
 */
public class UdpPacket {
    /**
     * 组网内部报文
     */
    private DatagramPacket mPacket;
    private SocketAddress mSocketAddress;
    private Message mMessage;

    public UdpPacket() {

    }

    public UdpPacket(int packetLength) {
        setDatagramPacket(packetLength);
    }

    public UdpPacket setDefaultDatagramPacket() {
        setDatagramPacket(0);
        return this;
    }

    public UdpPacket setDatagramPacket(int packetLength) {
        if (packetLength > 0) {
            byte[] data = new byte[packetLength];
            mPacket = new DatagramPacket(data, data.length);
        } else {
            byte[] data = new byte[4096];
            mPacket = new DatagramPacket(data, data.length);
        }
        return this;
    }

    public Message getMessage() {
        return mMessage;
    }

    public UdpPacket setMessage(Message mMessage) {
        this.mMessage = mMessage;
        return this;
    }

    public SocketAddress getSocketAddress() {
        return mSocketAddress;
    }

    public UdpPacket setSocketAddress(SocketAddress mSocketAddress) {
        this.mSocketAddress = mSocketAddress;
        return this;
    }

    public DatagramPacket getPacket() {
        return mPacket;
    }

    public UdpPacket setPacket(DatagramPacket mPacket) {
        this.mPacket = mPacket;
        return this;
    }

    public boolean hasData() {
        return this.mPacket != null && this.mPacket.getLength() > 0;
    }

    public DatagramPacket create() {
        if (mPacket == null || mSocketAddress == null || mMessage == null) {
            throw new RuntimeException("mPacket or mSocketAddress or mMessage is null!");
        }
        mPacket.setSocketAddress(mSocketAddress);
        mPacket.setData(mMessage.encode());
        return mPacket;
    }

    /**
     * 总长度
     */
    public int getDataLength() {
        if (mMessage != null) {
            return mMessage.totalLength();
        }
        return 0;
    }

    public Object clone() {
        Object obj = null;
        try {
            obj = super.clone();
        } catch (CloneNotSupportedException e) {
            e.getMessage();
        }
        return obj;
    }
}
